import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public final class DownLoadUrl implements DownTools.DownLoadTask {

	private DownTools.DownLoadListener mDownLoadListener;
	private String mUrl;

	public void onStart(String url, DownTools.DownLoadListener listener) {
		mUrl = url;
		mDownLoadListener = listener;
	}

	@Override
	public void run() {
		onDownLoad();
	}

	@Override
	public void onDownLoad() {
		HttpURLConnection urlConnection = null;
		FileOutputStream fos = null;
		try {
			URL url = new URL(mUrl);
			urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.setRequestMethod("GET");
			InputStream in = urlConnection.getInputStream();
			byte[] buffer = new byte[1024];
			fos = new FileOutputStream("D:/test.jpg");
			int count = 0;
			while ((count = in.read(buffer)) != -1) {
				fos.write(buffer, 0, count);
			}
			if (count == -1) {
				if (mDownLoadListener != null) {
					mDownLoadListener.onSuccess();
				}
			}
			in = null;
			fos.flush();
		} catch (MalformedURLException e) {
			e.printStackTrace();
			if (mDownLoadListener != null) {
				mDownLoadListener.onError();
			}
		} catch (IOException e) {
			e.printStackTrace();
			if (mDownLoadListener != null) {
				mDownLoadListener.onError();
			}
		} finally {
			if (urlConnection != null) {
				urlConnection.disconnect();
			}
			urlConnection = null;
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			fos = null;
		}

	}
}
